package com.bookdresser.activities;

import java.io.File;
import java.io.FileOutputStream;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

import com.bookdresser.R;
import com.bookdresser.widget.ActionBar;
import com.bookdresser.widget.ActionBar.AbstractAction;

public class InfoActivity extends Activity {

	private ImageButton ib_takephoto;
	private ImageView iv_book_photo;

	private Bitmap bm = null;
	public static final int SCALE = 10;
	private String newPicPath;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_info);

		final ActionBar actionBar = (ActionBar) findViewById(R.id.actionbar);
		actionBar.setHomeAction(new BackAction());
		actionBar.setTitle("填写信息");

		ib_takephoto = (ImageButton) findViewById(R.id.ib_takephoto);
		ib_takephoto.setOnClickListener(new TakePhotoListener());
		iv_book_photo = (ImageView) findViewById(R.id.iv_book_photo);
	}

	private class BackAction extends AbstractAction {

		public BackAction() {
			super(R.drawable.bt_back);
		}

		@Override
		public void performAction(View view) {
			InfoActivity.this.finish();
		}

	}

	private class TakePhotoListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			Intent intent = new Intent();
			intent.setClass(InfoActivity.this, ChoosePhotoActivity.class);
			startActivityForResult(intent, 0);
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (data != null) {
			newPicPath = data.getStringExtra("photo");

			switch (resultCode) {
			case ChoosePhotoActivity.SELECT_PIC_BY_PICK_PHOTO_RESULT:
				Uri uri = Uri.parse(newPicPath);
				if (newPicPath.contains("content://media/")) {
					bm = getBitmapFromUri(uri);
				} else if (newPicPath.contains("file://")) {
					bm = getBitmapFromFile(uri.getPath());
				}
				System.out.println("SELECT_PIC_BY_PICK_PHOTO_RESULT");
				break;
			case ChoosePhotoActivity.SELECT_PIC_BY_TACK_PHOTO_RESULT:
				bm = getBitmapFromPath(newPicPath);
				savePicLocal(bm, newPicPath);
				System.out.println("SELECT_PIC_BY_TACK_PHOTO_RESULT");
				break;
			default:
				break;
			}
			iv_book_photo.setImageBitmap(bm);
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 通过uri获取图片
	 * 
	 * @param uri
	 *            图片的uri
	 * @return Bitmap
	 */
	private Bitmap getBitmapFromUri(Uri uri) {
		try {
			// 读取uri所在的图片
			Bitmap bitmap = MediaStore.Images.Media.getBitmap(
					this.getContentResolver(), uri);
			Bitmap smallMap = zoomBitMap(bitmap, bitmap.getWidth() / SCALE,
					bitmap.getHeight() / SCALE);
			return smallMap;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	private Bitmap getBitmapFromFile(String filePath) {
		try {
			// 读取path所在的图片
			Bitmap bitmap = BitmapFactory.decodeFile(filePath);
			Bitmap smallMap = zoomBitMap(bitmap, bitmap.getWidth() / SCALE,
					bitmap.getHeight() / SCALE);
			return smallMap;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 通过文件路径获取图片
	 * 
	 * @param picName
	 *            图片的名称
	 * @return Bitmap
	 */
	private Bitmap getBitmapFromPath(String picName) {
		try {
			// 读取path所在的图片
			Bitmap bitmap = BitmapFactory.decodeFile(Environment
					.getExternalStorageDirectory().getPath() + "/" + picName);
			Bitmap smallMap = zoomBitMap(bitmap, bitmap.getWidth() / SCALE,
					bitmap.getHeight() / SCALE);
			return smallMap;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 压缩图片
	 * 
	 * @param bitMap
	 *            压缩对象
	 * @param width
	 *            图片的宽度
	 * @param height
	 *            图片的高度
	 * @return Bitmap 压缩后的图片
	 */
	private Bitmap zoomBitMap(Bitmap bitMap, int width, int height) {

		int w = bitMap.getWidth();
		int h = bitMap.getHeight();
		Matrix matrix = new Matrix();
		float scaleWidth = ((float) width / w);
		float scaleHeight = ((float) height / h);
		matrix.postScale(scaleWidth, scaleHeight);// 利用矩阵进行缩放不会造成内存溢出
		Bitmap newbmp = Bitmap.createBitmap(bitMap, 0, 0, w, h, matrix, true);
		return newbmp;
	}

	/**
	 * 将图片存到本地
	 * 
	 * @param btp
	 * @return 图片的路径
	 */
	private String savePicLocal(Bitmap bm, String newPicPath) {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			String path = Environment.getExternalStorageDirectory().getPath();
			String flieName = newPicPath;
			File upLoadFile = new File(path, flieName);
			String filePath = upLoadFile.getAbsolutePath();

			try {
				FileOutputStream fs = new FileOutputStream(upLoadFile);
				bm.compress(CompressFormat.JPEG, 100, fs);
				return filePath;
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
		} else {
			Toast.makeText(InfoActivity.this, "sd不存在", Toast.LENGTH_LONG)
					.show();
			return null;
		}

	}
}
